/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nokia.iap.ui.lib.onebutton;

import com.nokia.mid.ui.CanvasGraphicsItem;
import com.nokia.mid.ui.DirectUtils;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;

/**
 *
 * @author zinin
 */
public abstract class GxButtonBase extends CanvasGraphicsItem implements GxControl{
    protected final GxButtonDrawer drawer;
    private final int margin = 5;

    GxColorTheme theme = null;
    
    public GxButtonBase(String label, int x, int y, GxColorTheme colour){
        super(10, 10);
        theme = colour;
        Font font = theme.getFont();
        int fontHeight = font.getHeight();
        int height = fontHeight + margin * 2;
        int width = (int) (fontHeight * 0.75 * label.length() + margin * 2);
        
        setSize(width, height);
        
        drawer = new GxButtonDrawer(label, margin, x, y, width, height, font);
        drawer.setToggleable(true);
        
        setVisible(true);
    }

    protected void paint(Graphics g) {
        if(isVisible())
            drawer.render(g);
    }
    
    public void setPosition(int x, int y){
        super.setPosition(x, y);
        drawer.setX(x);
        drawer.setY(y);
    }

    public void setFocus(boolean isFocused) {
        drawer.setFocused(isFocused);
    }
    
    public boolean onTouch(int x, int y) {
        boolean result = false;
        if(isVisible()) {
            drawer.touchDown(x, y);
            if(drawer.isPressed()){
                performAction();
                drawer.setPressed(false);
                result = true;
            }
        }
        return result;
    }

    public void execute() {
        if(!(drawer.isFocused() && isVisible()))
            return;
        
        drawer.setPressed(!drawer.isPressed());
        performAction();
    }

    public abstract void performAction();
}
